package com.ykdl.member.kid.gears;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;

import com.sitech.oncon.barcode.core.CaptureActivity;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.MyCardAdapter;
import com.ykdl.member.kid.adapters.MyCard_Gallery_Adaper;
import com.ykdl.member.kid.beans.ArticleBean;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.beans.Point_typeBean;
import com.ykdl.member.kid.beans.Show_ScoreBean;
import com.ykdl.member.kid.beans.StoreInfoBean;
import com.ykdl.member.kid.gears.GoodLifeActivity.getDataTag;
import com.ykdl.member.kid.marketcard.CardInfoActivity;
import com.ykdl.member.kid.marketcard.IntegralDetailsActivity;
import com.ykdl.member.kid.marketcard.MarketcardHelpAandIntro;
import com.ykdl.member.kid.marketcard.MyCardActivity;
import com.ykdl.member.kid.marketcard.MyCouponActivity;
import com.ykdl.member.kid.marketcard.MyOrderActivity;
import com.ykdl.member.kid.marketcard.NearbyCardActivity;
import com.ykdl.member.kid.marketcard.NewStoreCoupon;
import com.ykdl.member.kid.widget.MyAdGallery;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.member.views.IndexViewPager;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;

import com.sitech.oncon.barcode.core.CaptureActivity;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.MyCardAdapter;
import com.ykdl.member.kid.adapters.MyCard_Gallery_Adaper;
import com.ykdl.member.kid.beans.ArticleBean;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.beans.Point_typeBean;
import com.ykdl.member.kid.beans.Show_ScoreBean;
import com.ykdl.member.kid.beans.StoreInfoBean;
import com.ykdl.member.kid.gears.GoodLifeActivity.getDataTag;
import com.ykdl.member.kid.marketcard.CardInfoActivity;
import com.ykdl.member.kid.marketcard.IntegralDetailsActivity;
import com.ykdl.member.kid.marketcard.MarketcardHelpAandIntro;
import com.ykdl.member.kid.marketcard.MyCardActivity;
import com.ykdl.member.kid.marketcard.MyCouponActivity;
import com.ykdl.member.kid.marketcard.MyOrderActivity;
import com.ykdl.member.kid.marketcard.NearbyCardActivity;
import com.ykdl.member.kid.marketcard.StoreCouponActivity;
import com.ykdl.member.kid.widget.MyAdGallery;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.member.views.IndexViewPager;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyGoodLifeActivity extends BaseScreen implements View.OnClickListener{
	private RefreshListView pull_refresh_listview; 
	private MyCardAdapter adapter;
	private Gallery mygallery;
	private View view;
	private IndexViewPager mViewPager;
	 private ViewPagerAdapter mVpAdapter;
	 private int mCurrentViewID = 0;         //当前页面
	 private int mMyDuration = 30;          //持续时间
	 private int PAGER_NUM = 2;
	 private FixedSpeedScroller mScroller;
	 private ArrayList<Point_typeBean>  point_type_list = new ArrayList<Point_typeBean>();
	 private IaskMenuBarView iask_menu_bar ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTopTitle("惠生活", 0, 0, null, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.mygoodlifeactivity_xml);
		initViews();
		getData();
	}

	private void initViews() {
		// TODO Auto-generated method stub
		iask_menu_bar = (IaskMenuBarView)findViewById(R.id.iask_menu_bar);
		iask_menu_bar.setSelectedID(R.id.bar_askdoctor);
		iask_menu_bar.setBaseScreen(this);
		pull_refresh_listview=(RefreshListView) findViewById(R.id.pull_refresh_list);
		view = LayoutInflater.from(this).inflate(R.layout.mygoodlifelist_head_view, null);
//		mygallery = (Gallery) view.findViewById(R.id.mygallery);
		mViewPager = (IndexViewPager)  view.findViewById(R.id.viewpager);
		view.findViewById(R.id.right_bt).setOnClickListener(this);
		view.findViewById(R.id.left_bt).setOnClickListener(this);
		view.findViewById(R.id.saojifen).setOnClickListener(this);
		view.findViewById(R.id.my_youhui).setOnClickListener(this);
		view.findViewById(R.id.my_order).setOnClickListener(this);
		mVpAdapter = new ViewPagerAdapter();
		 mViewPager.setAdapter(mVpAdapter);
		pull_refresh_listview.addHeaderView(view);
		pull_refresh_listview.setMoreButtoStlye();
		pull_refresh_listview.setMoreClick(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				go(NearbyCardActivity.class);
				pull_refresh_listview.onRefreshComplete();
				pull_refresh_listview.setFecthMoreOk();
			}});
		adapter = new MyCardAdapter(this);
		pull_refresh_listview.setAdapter(adapter);
		 try {             
			   Field mField = ViewPager.class.getDeclaredField("mScroller");             
			   mField.setAccessible(true);   
			    //设置加速度 ，通过改变FixedSpeedScroller这个类中的mDuration来改变动画时间（如mScroller.setmDuration(mMyDuration);） 
			mScroller = new FixedSpeedScroller(mViewPager.getContext(), new AccelerateInterpolator());        
			   mField.set(mViewPager, mScroller);         
			   } catch (Exception e) {         
			    e.printStackTrace();
			   }
		 pull_refresh_listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					Log.e("alan", "-------OnItemClick------arg2:"+arg2);
					StoreInfoBean bean= (StoreInfoBean)adapter.getItem(arg2-1);
					if (bean.getStatus()!=2) {
						Toast.makeText(mContext, "该门店不能提供服务", 1).show();
						return;
					}
					Intent intent = new Intent(MyGoodLifeActivity.this,NewStoreCoupon.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(KidAction.STORE_ID, bean.getStore_id()+"");
					intent.putExtra(KidAction.STORE_NAME, bean.getStore_name()+"");
					startActivity(intent);
				}
				
			});
		 pull_refresh_listview.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				getData();
			}
			 
		 });
//		mygallery.setAdapter(galler_adapter);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		getData();
		super.onResume();
		
	}
	public void getData() {
		showProgress("正在加载中,请稍等...");
		String  pageurl =KidConfig.GET_CARD_SCORE;
		HttpParameters parameterss = new HttpParameters();
		HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl,parameterss,null);
		 TaskManager.startHttpRequest(request, new getDataTag(),  Show_ScoreBean.class);
	}
	
	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof Show_ScoreBean) {
				Show_ScoreBean bean = (Show_ScoreBean)t;
				if (null==bean.getError()) {
					setData(bean);
					pull_refresh_listview.onRefreshComplete();
					pull_refresh_listview.setFecthMoreOk();
				}else {
					Toast.makeText(mContext, "加载失败,"+bean.getDesc(), 1).show();
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void setData(Show_ScoreBean bean) {
		this.point_type_list = bean.getPoint_type_list();
		if (bean.getCard_ids().size()==5) {
			pull_refresh_listview.setMoreButtoIsGon(true,"");
		}
		ArrayList<StoreInfoBean> list=bean.getCard_ids();
		
		if(list.size()>1){
			StoreInfoBean bean2=list.get(list.size()-1);
			list.add(bean2);
		}
		adapter.setList(list);
		mVpAdapter.setList(bean.getPoint_type_list());
		mVpAdapter.notifyDataSetChanged();
		 mViewPager.setAdapter(mVpAdapter);
		adapter.notifyDataSetChanged();
	}
	class ViewPagerAdapter extends PagerAdapter
	{
		final int[] navigation_res = { R.drawable.yuan1, R.drawable.yuan2, R.drawable.yuan3};
		private ArrayList<Point_typeBean>   list;
	    public void setList(ArrayList<Point_typeBean> list) {
			this.list = list;
			
		}
	    /**
	     * 获取当前页面数
	     */
	    @Override
	    public int getCount()
	    {
	    	if (list==null) {
				return 0;
			}else {
				return list.size();
			}
	    }
	    
	    @Override
	    public boolean isViewFromObject(View view, Object object)
	    {
	        
	       // Log.v(TAG, "isViewFromObject" + (view == object));
	        return view == object;
	    }
	    /**
	     * 适配器给container容器添加视图
	     */
	    @Override
	    public Object instantiateItem(ViewGroup container, int position)
	    {
	        Log.v(TAG, "instantiateItem" + position);
	        ViewHolder holder = null;
	        View convertView = RelativeLayout.inflate(mContext,
					R.layout.mygoodlife_lunxun, null);
			holder = new ViewHolder();
			holder.store_bg = (RelativeLayout) convertView.findViewById(R.id.store_bg);
			holder.score = (TextView) convertView.findViewById(R.id.score);
			holder.store_name = (TextView) convertView.findViewById(R.id.store_name);
	        container.addView(convertView, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
	        holder.score.setText(list.get(position).getScore());
	        holder.store_name.setText(list.get(position).getName());
	        holder.store_bg.setTag(list.get(position));
	        holder.store_bg.setBackgroundResource(navigation_res[(int) (3*Math.random())]);	        
	        holder.store_bg.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Point_typeBean bean= (Point_typeBean)v.getTag();
					String point_type_id = bean.getPoint_type_id();
					Intent intent = new Intent(MyGoodLifeActivity.this,IntegralDetailsActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("Point_typeBean",  (Serializable)bean);
					startActivity(intent);
				}
			});
	        return convertView;
	        
	    }
	    /**
	     * 适配器移除container容器中的视图
	     */
	    @Override
	    public void destroyItem(ViewGroup container, int position, Object object)
	    {
	    	container.removeView((View) object);        
	    }  
	    class ViewHolder {
			RelativeLayout store_bg;
			TextView score;
			TextView store_name;
			
		}

	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.left_bt:
			Log.e("alan", "------left---onClick----------");
			 if(mCurrentViewID != 0){
			     mCurrentViewID--;
			     mViewPager.setCurrentItem(mCurrentViewID, true);
			    }else {
			    	Toast.makeText(mContext, "已经是第一页", 1).show();
				}
			    mMyDuration -= 100;
			    mScroller.setmDuration(mMyDuration);
			break;
		case R.id.right_bt:
			if (point_type_list.size()>0) {
				PAGER_NUM= point_type_list.size();
			}
			if(mCurrentViewID != PAGER_NUM-1){
			     mCurrentViewID++;
			     mViewPager.setCurrentItem(mCurrentViewID, true);
			    }else {
			    	Toast.makeText(mContext, "已经是最后一页", 1).show();
				}
			    mMyDuration += 100;
			    mScroller.setmDuration(mMyDuration);
			break;
			case R.id.saojifen:
				Intent intent = new Intent(mContext,MarketcardHelpAandIntro.class);
				intent.putExtra(KidAction.IS_GONE_BT, true);
				startActivity(intent);
				break;
//			case R.id.go_help: //帮助
//				Intent intent1 = new Intent(mContext,MarketcardHelpAandIntro.class);
//				intent1.putExtra(KidAction.IS_GONE_BT, false);
//				startActivity(intent1);
//				break;
			case R.id.my_youhui:   //优惠
				Intent intent1 = new Intent(mContext,MyCouponActivity.class);
				intent1.putExtra(KidAction.IS_GONE_BT, true);
				startActivity(intent1);
				break;
			case R.id.my_order:   //订单
				Intent intent2 = new Intent(mContext,MyOrderActivity.class);
				startActivity(intent2);
				break;
		default:
			break;
		}
	}
	private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener(){

		   @Override
		   public void onPageScrollStateChanged(int arg0) {
		    // TODO Auto-generated method stub
		   }

		   @Override
		   public void onPageScrolled(int arg0, float arg1, int arg2) {
		    // TODO Auto-generated method stub
		   }
		   @Override
		   public void onPageSelected(int currentID) {
		    // TODO Auto-generated method stub
		    mCurrentViewID = currentID;
		   }};
	class FixedSpeedScroller extends Scroller {      
		private int mDuration = 1500;      
		public FixedSpeedScroller(Context context) {         
			super(context);     
			}      
		public FixedSpeedScroller(Context context, Interpolator interpolator) {         
			super(context, interpolator);     
			}      
		     
		@Override    
		public void startScroll(int startX, int startY, int dx, int dy, int duration) {    
			// Ignore received duration, use fixed one instead         
			super.startScroll(startX, startY, dx, dy, mDuration);     
			}      
		@Override     
		public void startScroll(int startX, int startY, int dx, int dy) {        
				// Ignore received duration, use fixed one instead        
				super.startScroll(startX, startY, dx, dy, mDuration);    
				} 
		public void setmDuration(int time){
			mDuration = time;
		}	
		public int getmDuration(){
			return mDuration;
		}	

	}
	
}
